package com.example.bookmanage.controller;

import com.example.bookmanage.pojo.Book;
import com.example.bookmanage.service.BookService;
import com.example.bookmanage.service.ex.insertException;
import com.example.bookmanage.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("books")
public class BookController {
    private BookService bookService;
    @Autowired
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }
    @RequestMapping("queryAllBook")
    public JsonResult<Book> queryAllBook(String page,String limit,String time1,String time2){
        //从外界传过来四个参数 对传进来的数据进行逻辑处理
        if (page==null||"".equals(page)){
            page="1";
        }
        if (limit==null||"".equals(limit)){
            limit="10";
        }
        //将参数传到service层
        //但是如果
        if (time1==null||"".equals(time1)){
            time1="";
        }
        if (time2==null||"".equals(time2)){
            time2="";
        }
        return bookService.findData(Integer.parseInt(page), Integer.parseInt(limit), time1, time2);
    }
    //前台删除一本书籍
    @RequestMapping("deleteBook")
    public void deleteBook(Integer id){
        bookService.delete(id);
    }
    //前台增加一本书
    @RequestMapping("addBook")
    public JsonResult<Void> addBook(Book book){
        JsonResult<Void> result = new JsonResult<>();
        try{
            bookService.insertBook(book);
            result.setCode(200);
            result.setMsg("增加成功");
        }catch (insertException e){
            result.setCode(400);
            result.setMsg("该书籍已经存在了");
        }
        return result;
    }
    //接口查询成功
    @RequestMapping("queryBookByBookName")
    public JsonResult<Book> queryBookByBookName(String bookName){
        return bookService.queryBookByName(bookName);
    }
    @RequestMapping("update")
    public String update(Book book){
        String msg;
        if (bookService.updateBook(book)){
            msg="跟新成功";
        }else {
            msg="跟新失败";
        }
        return  msg;
    }
}
